import React, { useEffect } from 'react';
import { request } from 'ice';
import { Button, Dialog, Form, Field, Input, Upload } from '@alifd/next';
import moment from 'moment';
import { DialogProps } from '@alifd/next/types/dialog';

export type ActionType = 'add' | 'edit' | 'preview';

export interface OperationProps {
  action: ActionType | undefined;
  item: any;
}

const getDialogTitle = (action: ActionType | undefined): string => {
  switch (action) {
    case 'add':
    default:
      return '添加视频';
    case 'edit':
      return '编辑视频';
    case 'preview':
      return '预览视频';
  }
};

const DialogOperation: React.FC<OperationProps & DialogProps & { submit: (values: any) => void }> = (props) => {
  const { action, item, submit, ...lastProps } = props;
  const field = Field.useField();
  useEffect(() => {
    field.reset();
    if (item) {
      const { url, ...rest } = item;
      field.setValues({
        file: url && [{ uid: url, name: '点击查看', url }],
        ...rest,
      });
    }
  }, [field, item]);

  const isPreview = action === 'preview';

  return (
    <Dialog
      shouldUpdatePosition
      isFullScreen
      title={getDialogTitle(action)}
      style={{ width: 600 }}
      footerAlign="center"
      onOk={() => {
        field.validate((err, values: any) => {
          const { file, ...rest } = values;
          if (!err && file[0].url) {
            submit({ url: file[0].url, ...rest });
          }
        });
      }}
      {...lastProps}
    >
      <Form isPreview={isPreview} labelAlign="left" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} field={field}>
        <Form.Item label="视频" required>
          <Upload
            listType="text"
            accept="video/*"
            limit={1}
            withCredentials={false}
            beforeUpload={async (file: any, options: any) => {
              const mts = +moment();
              const idx = file.name.lastIndexOf('.');
              let name: string;
              if (idx < 0) {
                name = `${file.name}_${mts}`;
              } else {
                const prefix = file.name.substr(0, idx);
                const suffix = file.name.substr(idx + 1);
                name = `${prefix}_${mts}.${suffix}`;
              }
              const key = `video/${name}`;

              const { host, AccessKeyId, policy, signature } = await request.get('/api/obssign');
              options.data = {
                key,
                AccessKeyId,
                policy,
                signature,
              };
              options.headers = { 'X-Requested-With': null };
              options.action = host;
              file.tempUrl = `${host}/${key}`;
              return options;
            }}
            formatter={(res, file) => ({
              success: true,
              url: file.tempUrl,
            })}
            {...field.init('file', { rules: [{ required: true, message: '请选择文件' }] })}
          >
            <Button type="primary">上传文件</Button>
          </Upload>
        </Form.Item>
        <Form.Item label="名称" required>
          <Input {...field.init('name', { rules: [{ required: true, message: '必填' }] })} />
        </Form.Item>
        <Form.Item label="时长(秒)" required>
          <Input {...field.init('length', { rules: [{ required: true, format: 'number', message: '必须是数字' }] })} />
        </Form.Item>
        <Form.Item label="来源" required>
          <Input {...field.init('source', { rules: [{ required: true, message: '必填' }] })} />
        </Form.Item>
        <Form.Item label="标签" required>
          <Input {...field.init('tags', { rules: [{ required: true, message: '必填' }] })} />
        </Form.Item>
      </Form>
    </Dialog>
  );
};

export default DialogOperation;
